<template>
  <el-drawer
    v-model="drawerVisible"
    direction="rtl"
    size="700px"
    with-header
    :destroy-on-close="false"
    @close="handleClose"
  >
    <template #header>
      <div class="drawer-custom-header">
        <h3>患者病历总览</h3>
      </div>
    </template>

    <div class="drawer-content-wrapper" v-loading="loading">
      <!-- 患者基本信息卡片 -->
      <div class="patient-profile-card">
        <div class="profile-header">
          <el-avatar
            :size="80"
            :src="patientInfo.avatar"
            class="profile-avatar"
          >
            {{ patientInfo.patient_name?.charAt(0) }}
          </el-avatar>
          <div class="profile-info">
            <h2 class="patient-name">{{ patientInfo.patient_name }}</h2>
            <div class="patient-meta">
              <el-tag type="primary" size="small">
                {{ patientInfo.gender }} · {{ patientInfo.patient_age }}岁
              </el-tag>
              <span class="patient-phone">{{ patientInfo.phone_number }}</span>
            </div>
            <div class="patient-stats">
              <span class="stat-text">病历总数：{{ medicalRecords.length }} 次</span>
            </div>
          </div>
        </div>
        
        <div class="patient-tags" v-if="patientInfo.allergy_history || patientInfo.chronic_diseases">
          <el-tag
            v-if="patientInfo.allergy_history"
            type="danger"
            size="small"
          >
            过敏：{{ patientInfo.allergy_history }}
          </el-tag>
          <el-tag
            v-for="disease in patientInfo.chronic_diseases"
            :key="disease"
            type="warning"
            size="small"
          >
            {{ disease }}
          </el-tag>
        </div>
      </div>

      <!-- 病历列表 -->
      <div class="detail-sections">
        <div class="detail-section">
          <div class="section-header">
            <el-icon><Document /></el-icon>
            <span>历次就诊记录</span>
          </div>
          <div class="section-content">
            <div class="records-timeline">
              <div
                v-for="record in medicalRecords"
                :key="record.diagnosis_id"
                class="record-item"
                :class="{ current: record.isCurrent }"
              >
                <div class="timeline-marker"></div>
                <div class="record-content">
                  <div class="record-header">
                    <div class="record-date">
                      {{ formatDate(record.visit_time) }}
                    </div>
                    <div class="record-status">
                      <el-tag
                        :type="getRecordStatusType(record.diagnosis_status)"
                        size="small"
                      >
                        {{ getRecordStatusText(record.diagnosis_status) }}
                      </el-tag>
                    </div>
                  </div>

                  <div class="record-info">
                    <div class="diagnosis-info">
                      <strong>诊断：</strong>
                      <span class="diagnosis-text">{{ record.current_diagnosis }}</span>
                    </div>

                    <div class="record-meta">
                      <div class="meta-item">
                        <el-icon><User /></el-icon>
                        <span>接诊医生：{{ record.doctor_name }}</span>
                      </div>
                      <div class="meta-item">
                        <el-icon><OfficeBuilding /></el-icon>
                        <span>科室：{{ record.department_name }}</span>
                      </div>
                    </div>

                    <div class="treatment-summary" v-if="record.treatment_plan">
                      <strong>治疗方案：</strong>
                      <div class="treatment-content">
                        {{ record.treatment_plan }}
                      </div>
                    </div>
                  </div>

                  <div class="record-actions">
                    <el-button
                      type="primary"
                      link
                      size="small"
                      @click="handleViewDetail(record)"
                    >
                      <el-icon><View /></el-icon>
                      查看详情
                    </el-button>
                    <el-button
                      type="info"
                      link
                      size="small"
                      @click="handlePrintRecord(record)"
                    >
                      <el-icon><Printer /></el-icon>
                      打印病历
                    </el-button>
                  </div>
                </div>
              </div>

              <div v-if="medicalRecords.length === 0" class="no-records">
                <el-empty description="暂无就诊记录" />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </el-drawer>
</template>

<script setup>
import { ref, watch, computed } from "vue";
import { ElMessage } from "element-plus";
// 引入后端API接口
import { getPatientMasterAndRecordListDataById } from "@/api/doctor";

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  patientId: {
    type: Number,
    default: null,
  },
  patientInfo: {
    //患者信息对象
    type: Object,
    default: null,
  },
});

const emit = defineEmits(["update:modelValue", "recordSelected"]);

// 响应式数据
const drawerVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit("update:modelValue", value),
});

const loading = ref(false);
const patientInfo = ref({});
const medicalRecords = ref([]);

// 修改watch监听器，确保在抽屉打开时加载数据
watch(
  () => props.modelValue,
  (newValue) => {
    if (newValue && props.patientId) {
      loadMedicalRecords();
    }
  }
);

// 加载患者病历记录-就诊记录 1对多
const loadMedicalRecords = async () => {
  if (!props.patientId) return;

  loading.value = true;

  try {
    const params = {
      patient_id: props.patientId,
    };
    // TODO: 调用API获取患者病历记录
    const response = await getPatientMasterAndRecordListDataById(params);
    console.log("获取到的病历记录数据:", response);
    // 解析并赋值给patientInfo和medicalRecords
    if (response && response.code == 200) {
      // 应该改为：
      patientInfo.value = {
        ...response.data,
        age: response.data.patient_age, // 将 patient_age 映射为 age
        patient_name: response.data.patient_name,
      };

      medicalRecords.value = response.data.medicalRecords || [];
    }
  } catch (error) {
    ElMessage.error("获取病历记录失败");
  } finally {
    loading.value = false;
  }
};

const handleClose = () => {
  patientInfo.value = {};
  medicalRecords.value = [];
};

const handleViewDetail = (record) => {
  emit("recordSelected", {
    ...record,
    patient_name: patientInfo.value.patient_name,
    gender: patientInfo.value.gender,
    patient_age: patientInfo.value.patient_age,
    phone_number: patientInfo.value.phone_number,
  });
};

const handlePrintRecord = (record) => {
  ElMessage.success(`正在打印 ${formatDate(record.visit_time)} 的病历`);
};

const getRecordStatusType = (status) => {
  const typeMap = {
    completed: "success",
    in_progress: "primary",
    draft: "info",
  };
  return typeMap[status] || "info";
};

const getRecordStatusText = (status) => {
  const textMap = {
    completed: "已完成",
    in_progress: "进行中",
    draft: "草稿",
  };
  return textMap[status] || status;
};

const formatDate = (dateString) => {
  return dateString;
};
</script>

<style lang="scss" scoped>
// 抽屉自定义头部
.drawer-custom-header {
  h3 {
    margin: 0;
    color: #303133;
    font-size: 18px;
    font-weight: 600;
  }
}

.drawer-content-wrapper {
  padding: 0 20px;
  height: 100%;
  overflow-y: auto;
}

// 患者信息卡片 - 医疗风格渐变
.patient-profile-card {
  background: linear-gradient(135deg, #e6a23c 0%, #e6c23c 100%);
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
  color: white;
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: -50%;
    right: -50%;
    width: 100%;
    height: 100%;
    background: rgba(255, 255, 255, 0.1);
    border-radius: 50%;
  }
}

.profile-header {
  display: flex;
  align-items: center;
  gap: 16px;
  position: relative;
  z-index: 1;
}

.profile-avatar {
  border: 3px solid rgba(255, 255, 255, 0.2);
  background: rgba(255, 255, 255, 0.2);
}

.profile-info {
  flex: 1;
  
  .patient-name {
    margin: 0 0 8px 0;
    font-size: 24px;
    font-weight: 600;
    color: white;
  }
  
  .patient-meta {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 8px;
    
    .patient-phone {
      font-size: 14px;
      opacity: 0.9;
    }
  }
  
  .patient-stats {
    .stat-text {
      font-size: 14px;
      opacity: 0.9;
    }
  }
}

.patient-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  margin-top: 12px;
  position: relative;
  z-index: 1;
}

// 详细信息区域
.detail-sections {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.detail-section {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid #f0f0f0;
}

.section-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f5f5f5;
  
  .el-icon {
    color: #e6a23c;
    font-size: 16px;
  }
  
  span {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
  }
}

.section-content {
  .records-timeline {
    position: relative;

    &::before {
      content: "";
      position: absolute;
      left: 16px;
      top: 0;
      bottom: 0;
      width: 2px;
      background: #e4e7ed;
    }
  }

  .record-item {
    position: relative;
    margin-bottom: 24px;
    padding-left: 40px;

    &.current {
      .timeline-marker {
        background: #e6a23c;
        border-color: #e6a23c;
      }
    }

    &:last-child {
      margin-bottom: 0;
    }
  }

  .timeline-marker {
    position: absolute;
    left: 8px;
    top: 8px;
    width: 16px;
    height: 16px;
    border: 3px solid #e4e7ed;
    border-radius: 50%;
    background: white;
    z-index: 1;
    transition: all 0.3s;
  }

  .record-content {
    background: #f8f9fa;
    border: 1px solid #ebeef5;
    border-radius: 8px;
    padding: 16px;
    transition: all 0.3s;

    &:hover {
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
      border-color: #e6a23c;
    }
  }

  .record-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;

    .record-date {
      font-weight: 600;
      color: #303133;
      font-size: 15px;
    }
  }

  .record-info {
    .diagnosis-info {
      margin-bottom: 12px;

      .diagnosis-text {
        color: #e6a23c;
        font-weight: 500;
      }
    }

    .record-meta {
      display: flex;
      flex-direction: column;
      gap: 6px;
      margin-bottom: 12px;

      .meta-item {
        display: flex;
        align-items: center;
        gap: 6px;
        font-size: 13px;
        color: #909399;

        .el-icon {
          font-size: 12px;
        }
      }
    }

    .treatment-summary {
      font-size: 13px;
      color: #606266;

      .treatment-content {
        background: white;
        padding: 8px 12px;
        border-radius: 6px;
        margin-top: 4px;
        border-left: 3px solid #e6a23c;
      }
    }
  }

  .record-actions {
    display: flex;
    gap: 16px;
    margin-top: 12px;
    padding-top: 12px;
    border-top: 1px solid #e8e8e8;
  }

  .no-records {
    padding: 40px 0;
    text-align: center;
  }
}

// 暗色主题适配
@media (prefers-color-scheme: dark) {
  .drawer-custom-header h3 {
    color: #e0e0e0;
  }
  
  .detail-section {
    background: #2d2d2d;
    border-color: #3d3d3d;
  }
  
  .section-header {
    border-bottom-color: #3d3d3d;
    
    span {
      color: #e0e0e0;
    }
  }
  
  .section-content {
    .record-content {
      background: #3d3d3d;
      border-color: #4d4d4d;
    }
    
    .record-header .record-date {
      color: #e0e0e0;
    }
    
    .diagnosis-info .diagnosis-text {
      color: #e6a23c;
    }
    
    .record-meta .meta-item {
      color: #a0a0a0;
    }
    
    .treatment-summary {
      color: #c0c0c0;
      
      .treatment-content {
        background: #3d3d3d;
        border-left-color: #e6a23c;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .drawer-content-wrapper {
    padding: 0 16px;
  }
  
  .profile-header {
    flex-direction: column;
    text-align: center;
  }
  
  .patient-meta {
    justify-content: center;
    flex-wrap: wrap;
  }
  
  .record-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .record-actions {
    flex-direction: column;
    gap: 8px;
  }
  
  .detail-section {
    padding: 16px;
  }
}
</style>